import { NestFactory } from '@nestjs/core';
import { AppModule, IS_DEV } from './app.module';
import { Logger } from '@nestjs/common';
import * as process from 'node:process';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import rateLimit from 'express-rate-limit';
import { AllExceptionsFilter } from './util/GloableFilter';
import { LoggingInterceptor } from './auth/filter-login/LoginFilter';
import { HttpExceptionFilter } from './util/HttpExceptionFilter';

const PREFIX = process.env.PREFIX || '/';
const PORT = process.env.PORT || 3000;
console.log(PREFIX);
console.log(process.env.HOST);
async function bootstrap() {
  // 根据 RUNNING_ENV 设置日志级别
  let loggerOptions;
  if (IS_DEV === 'dev') {
    loggerOptions = ['log', 'debug', 'error', 'warn']; // 开发环境：启用所有日志
  } else if (IS_DEV === 'test') {
    loggerOptions = ['log', 'error', 'warn']; // 测试环境：启用日志、错误和警告
  } else {
    loggerOptions = ['error', 'warn', 'log']; // 生产环境：仅启用错误和警告日志
  }

  const [app] = await Promise.all([
    NestFactory.create(AppModule, {
      logger: loggerOptions,
    }),
  ]);

  app.enableCors({
    origin: '*',
    credentials: true,
    "allowedHeaders":['Authorization','content-type'],
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    preflightContinue: false,
    optionsSuccessStatus: 204,
  });
  // 创建 Swagger 选项
  const options = new DocumentBuilder()
    .setTitle('Example API')
    .setDescription('The example API description')
    .setVersion('1.0')
    .addTag('example')
    .build();
  // 创建 Swagger 文档
  const document = SwaggerModule.createDocument(app, options);
  // 设置 `/api` 路由为 Swagger 文档及其 UI 的主页
  SwaggerModule.setup(process.env.SWAGGERURL || 'doc-ui', app, document);
  const logger: Logger = new Logger('main.ts');
  // 全局注册异常过滤器
  app.useGlobalFilters( new HttpExceptionFilter(),new AllExceptionsFilter());
  // 登录拦截器
  app.useGlobalInterceptors(new LoggingInterceptor());
  // @ts-ignore
  // 设置项目的前缀
  app.setGlobalPrefix(PREFIX);
  // @ts-ignore
  await app.listen(PORT, () => {
    logger.log(`Server started on port ${PORT},${PREFIX}`);
  });
  app.use(
    rateLimit({
      windowMs: 15 * 60 * 1000, // 15分钟
      max: 1000, // 限制15分钟内最多只能访问1000次
    }),
  );
  if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => app.close());
  }
}

const logger:Logger = new Logger();
bootstrap().then(r => {
  logger.log('bootstrap started on port ' + PORT);
});
